package com.jyy.prefabricated.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.Pageable;
import com.jyy.prefabricated.dto.ResetPwdDto;
import com.jyy.prefabricated.dto.StudentDto;
import com.jyy.prefabricated.dto.StudentRegisterDto;
import com.jyy.prefabricated.entity.Student;
import com.jyy.prefabricated.entity.SysUser;
import com.jyy.prefabricated.entity.TrainingOrganization;
import com.jyy.prefabricated.enums.UserTypeEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.service.SmsRecordService;
import com.jyy.prefabricated.service.StudentService;
import com.jyy.prefabricated.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private SmsRecordService smsRecordService;

    @Autowired
    private UserUtils userUtils;

    /**
     * 学员注册
     *
     * @param dto
     * @return
     */
    @PostMapping("/students-register")
    public AjaxResult registerStudent(@Valid @RequestBody StudentRegisterDto dto) {
        log.info("Rest request to register student:{}", dto);
        smsRecordService.checkCode(dto.getTel(), dto.getValidateCode());
        Student student = studentService.studentRegister(dto);
        return AjaxResult.success(student);
    }

    /**
     * 新增学员
     *
     * @param dto
     * @return
     */
    @PostMapping("/students")
    public AjaxResult insert(@Valid @RequestBody StudentDto dto) {
        log.info("Rest request to insert student:{}", dto);
        //控制新增学员权限
        SysUser user = userUtils.getCurrentUser();
        if (!UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            //当前用户不是培训机构
            throw new CustomException(403, "当前用户无权限添加学员");
        }
        TrainingOrganization trainingOrganization = user.getTrainingOrganization();
//        List<Student> list = studentService.selectByParams(null,null,null,null,null,trainingOrganization.getId());
//        if(list.size() >= trainingOrganization.getAccountNum()){
//            throw new CustomException(403,"账号数量不足！");
//        }
        dto.setTrainingOrganizationId(trainingOrganization.getId());
        int id = studentService.insert(dto);
        Student result = studentService.selectById(id);
        return AjaxResult.success(result);
    }

    /**
     * 更新学员
     *
     * @param dto
     * @return
     */
    @PutMapping("/students")
    public AjaxResult update(@Valid @RequestBody StudentDto dto) {
        log.info("Rest request to update student:{}", dto);
        studentService.update(dto);
        Student result = studentService.selectById(dto.getId());
        return AjaxResult.success(result);
    }

    /**
     * 判断手机号是否已存在
     *
     * @return
     */
    @GetMapping("/students-tel/{id}/{tel}")
    public AjaxResult judgeTel(@PathVariable Integer id, @PathVariable String tel) {
        studentService.judgeTel(id, tel);
        return AjaxResult.success();
    }

    /**
     * 重置学员密码
     *
     * @param dto
     * @return
     */
    @PutMapping("/students-pwd")
    public AjaxResult resetPwd(@RequestBody ResetPwdDto dto) {
        log.info("Rest request to reset students-pwd:{}", dto);
        int row = studentService.resetStudentPwd(dto.getAccount(), dto.getPassword());
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }


    /**
     * 学员主动找回密码
     *
     * @param dto
     * @return
     */
    @PutMapping("/students-repwd")
    public AjaxResult retrievePwd(@Valid @RequestBody StudentRegisterDto dto) {
        log.info("Rest request to reset students-pwd:{}", dto);
        smsRecordService.checkCode(dto.getTel(), dto.getValidateCode());
        int row = studentService.resetStudentPwd(dto.getTel(), dto.getPassword());
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 更新学员状态
     *
     * @param id
     * @return
     */
    @PutMapping("/students-status/{id}")
    public AjaxResult update(@PathVariable Integer id) {
        log.info("Rest request to update student-status by id:{}", id);
        int row = studentService.updateStatus(id);
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 获取学员详情
     *
     * @param id
     * @return
     */
    @GetMapping("/students/{id}")
    public AjaxResult selectById(@PathVariable Integer id) {
        log.info("Rest request to find student by id:{}", id);
        Student result = studentService.selectById(id);
        return AjaxResult.success(result);
    }

    /**
     * 分页查询学员
     *
     * @param name                   姓名
     * @param idCard                 身份证
     * @param tel                    电话
     * @param status                 状态
     * @param projectId              项目id
     * @param trainingOrganizationId 机构id
     * @param pageable               分页信息
     * @return
     */
    @GetMapping("/students")
    public AjaxResult selectByParams(@RequestParam(required = false, defaultValue = "") String name, @RequestParam(required = false, defaultValue = "") String idCard, @RequestParam(required = false, defaultValue = "") String tel, @RequestParam(required = false) Integer status, @RequestParam(required = false) Integer projectId, @RequestParam(required = false) Integer trainingOrganizationId, Pageable pageable) {
        log.info("Rest request to find students by params tel:{},startDate:{},endDate:{}", name, idCard, tel, status, projectId, trainingOrganizationId);
        SysUser user = userUtils.getCurrentUser();
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            //如果当前用户是培训机构,培训机构职能查看自己名下的学生
            trainingOrganizationId = user.getTrainingOrganization().getId();
        }
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Student> student = studentService.selectByParams(name, idCard, tel, status, projectId, trainingOrganizationId);
        PageInfo<Student> result = new PageInfo<>(student);
        return AjaxResult.success(result);
    }


    /**
     * 分页查询企业学员
     *
     * @param name                   姓名
     * @param idCard                 身份证
     * @param tel                    电话
     * @param status                 状态
     * @param projectId              项目id
     * @param trainingOrganizationId 机构id
     * @param pageable               分页信息
     * @return
     */
    @GetMapping("/organization-students")
    public AjaxResult selectByParam(@RequestParam(required = false, defaultValue = "") String name, @RequestParam(required = false, defaultValue = "") String idCard, @RequestParam(required = false, defaultValue = "") String tel, @RequestParam(required = false) Integer status, @RequestParam(required = false) Integer projectId, @RequestParam(required = false) Integer trainingOrganizationId, Pageable pageable) {
        log.info("Rest request to find students by params tel:{},startDate:{},endDate:{}", name, idCard, tel, status, projectId, trainingOrganizationId);

        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Student> student = studentService.selectByParams(name, idCard, tel, status, projectId, trainingOrganizationId);
        PageInfo<Student> result = new PageInfo<>(student);
        return AjaxResult.success(result);
    }


    /**
     * 查询学员
     *
     * @param name                   姓名
     * @param idCard                 身份证
     * @param tel                    电话
     * @param status                 状态
     * @param projectId              项目id
     * @param trainingOrganizationId 机构id
     * @return
     */
    @GetMapping("/students-list")
    public AjaxResult selectByParams(@RequestParam(required = false, defaultValue = "") String name, @RequestParam(required = false, defaultValue = "") String idCard, @RequestParam(required = false, defaultValue = "") String tel, @RequestParam(required = false) Integer status, @RequestParam(required = false) Integer projectId, @RequestParam(required = false) Integer trainingOrganizationId) {
        log.info("Rest request to find students by params tel:{},startDate:{},endDate:{}", name, idCard, tel, status, projectId, trainingOrganizationId);
        SysUser user = userUtils.getCurrentUser();
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            //如果当前用户是培训机构,培训机构职能查看自己名下的学生
            trainingOrganizationId = user.getTrainingOrganization().getId();
        }
        List<Student> student = studentService.selectByParams(name, idCard, tel, status, projectId, trainingOrganizationId);
        return AjaxResult.success(student);
    }
}
